const router = require("koa-router")()
const {
  createAddress,
  getAddressList,
  getAddressById,
  updateAddress
} = require("../controller/address")
const loginCheck = require("../middleware/loginCheck")
const { SuccessModel, ErrorModel } = require("../res-module/index")

router.prefix("/api/user/address")

// 创建
router.post("/", loginCheck, async function (ctx, next) {
  const userInfo = ctx.session.userInfo
  const username = userInfo.username
  const data = ctx.request.body || {}
  try {
    const newAdress = await createAddress(username, data)
    ctx.body = new SuccessModel(newAdress)
  } catch (error) {
    ctx.body = new ErrorModel(10004, `创建地址失败`)
  }
})
// 获取地址列表
router.get("/", loginCheck, async function (ctx, next) {
  const userInfo = ctx.session.userInfo
  const username = userInfo.username

  const list = await getAddressList(username)
  ctx.body = new SuccessModel(list)
})

// 获取单个地址
router.get("/:id", loginCheck, async function (ctx, next) {
  const id = ctx.params.id
  const address = await getAddressById(id)
  ctx.body = new SuccessModel(address)
})

// 更新收货地址
router.patch("/:id", loginCheck, async function (ctx, next) {
  const userInfo = ctx.session.userInfo
  const username = userInfo.username
  const id = ctx.params.id
  const data=ctx.request.body || {}

  const newAddress = await updateAddress(id,username,data)
  ctx.body = new SuccessModel(newAddress)
})

module.exports = router
